const { weather } = require("../input");
const axios = require("axios");

//获得城市代码，参数为城市名
const getCityCode = (cityName) => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await axios.get(`https://geoapi.qweather.com/v2/city/lookup?location=${encodeURI(weather.city, "gbk")}&key=${weather.key}`);
      // console.log('城市代码', res.data);
      if (res.data.code == 200) {
        resolve(res.data.location[0].id);
      } else {
        reject(res.data);
      }
    } catch (error) {
      console.log("获取城市代码失败", error.message || error);
      reject(error.message || error);
    }
  });
};

//获得天气数据
const getWeather = (cityName, index = 0) => {
  return new Promise(async (resolve, reject) => {
    try {
      const cityId = await getCityCode(cityName);
      //多请求并行
      const weatherReq = axios(`https://devapi.qweather.com/v7/weather/3d?key=${weather.key}&location=${cityId}`); //这是三天的天气预报
      // const indicesReq = axios(`https://devapi.qweather.com/v7/indices/1d?key=${weather.key}&location=${cityId}&type=${'3'}`)//这是今天的天气指数
      const weatherRes = await weatherReq; //三天天气
      // const indicesRes = await indicesReq//天气指数，暂时没发现有啥用

      if (weatherRes.data.code == 200) {
        // && indicesRes.data.code == 200
        const data = {
          daily: weatherRes.data.daily[index], //index日天气
          fxLink: weatherRes.data.fxLink, //天气网站
        };
        console.log("获取今日天气成功", data.fxLink);
        resolve(data);
      } else {
        reject(weatherRes.data);
      }
    } catch (error) {
      console.log("获取今日天气失败", error.message || error);
      reject(error.message || error);
    }
  });
};

//处理天气数据
module.exports = handleWeather = () => {
  return new Promise(async (resolve, reject) => {
    try {
      const { daily, fxLink } = await getWeather(weather.city, parseInt(weather.index));
      const day = ["今日", "明日", "后天"][weather.index]; //显示第几天
      const weatherContent = `🌍${weather.city}${day}天气: \n· ${day}气温${daily.tempMin} ~ ${daily.tempMax}℃  ${daily.textDay}\n· ${day}风况 ${
        daily.windDirDay
      } ${daily.windScaleDay}级 \n${daily.iconDay >= 300 && daily.iconDay < 400 ? `· ${day}有雨, 出门记得带伞哦\n` : ""}· 详情${fxLink}`;
      resolve(weatherContent);
    } catch (error) {
      console.log("处理天气数据失败", error.message || error);
      // reject(error.message || error)
      resolve(`处理天气数据失败: ${error.message || error}`);
    }
  });
};
